﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autofac;
using Pay.DTO;
using Pay.IService;
using Pay.TO;
using Pay.Core;

namespace Pay.Token {
    /// <summary>
    /// 分销统一接口
    /// </summary>
    public interface IDistribution {
        /// <summary>
        /// 分润计算
        /// </summary>
        /// <param name="merchant_id"></param>
        /// <param name="order_item"></param>
        /// <param name="is_distribute"></param>
        /// <returns></returns>
        List<bind_merchant_item> Handler(long merchant_id, order_item_dto order_item, bool is_distribute = true);
    }
    /// <summary>
    /// 分润基类
    /// </summary>
    public class DistributionBase {
        /// <summary>
        /// 
        /// </summary>
        private IProductService _iProductService;
        /// <summary>
        /// 
        /// </summary>
        private IMerchantService _iMerchantService;
        /// <summary>
        /// 分润集合
        /// </summary>
        protected List<bind_merchant_item> binds;
        /// <summary>
        /// 已分配用户
        /// </summary>
        protected Dictionary<UserType, merchant_dto> dicUses;
        /// <summary>
        /// 是否已经分配间接分润
        /// </summary>
        protected bool is_finish;
        /// <summary>
        /// 
        /// </summary>
        protected ILogHelper log;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="iMerchantService"></param>
        /// <param name="iProductService"></param>
        public DistributionBase(IMerchantService iMerchantService, IProductService iProductService) {
            _iProductService = iProductService;
            _iMerchantService = iMerchantService;
            binds = new List<bind_merchant_item>();
            dicUses = new Dictionary<UserType, merchant_dto>();
            log = IocHelper.Get<ILogHelper>("info");
        }
        /// <summary>
        /// 计算自己获得分润
        /// </summary>
        /// <param name="merchant_id"></param>
        /// <param name="amount"></param>
        /// <param name="order_item"></param>
        /// <param name="percent"></param>
        /// <param name="is_bus"></param>
        protected void CalcSelfProfit(long merchant_id, decimal amount, order_item_dto order_item, decimal percent, bool is_bus = false) {
            var product = _iProductService.GetForActicity(order_item.product_id);
            var merchant = _iMerchantService.Get(merchant_id);
            if (amount > 0) {
                binds.Add(new bind_merchant_item {
                    merchant_no = merchant.merchant_no,
                    amount = amount,
                    product_id = order_item.product_id,
                    sku_id = order_item.sku_id ?? 0,
                    product_name = product.name,
                    freeze = true,
                    is_bus = is_bus
                });
                log.Info(string.Format("用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", merchant.name, merchant.usertype.ToDescription(), amount, percent));
            }
        }
        /// <summary>
        /// 上级用户
        /// </summary>
        /// <param name="merchant_id"></param>
        /// <param name="is_contain"></param>
        /// <returns></returns>
        protected IEnumerable<merchant_dto> GetParents(long merchant_id, bool is_contain = true) {
            return _iMerchantService.GetParents(merchant_id, is_contain);
        }
        /// <summary>
        /// 获取活动商品信息
        /// </summary>
        /// <param name="order_item"></param>
        /// <returns></returns>
        protected product_calculate_ex GetProduct(order_item_dto order_item) {
            return _iProductService.GetCalculateExForActivity(order_item.product_id, order_item.sku_id ?? 0, false,order_item.isCashPay);
        }
    }
    /// <summary>
    /// 普通用户分销
    /// </summary>
    public class TokenUserDistribution : DistributionBase, IDistribution {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="iMerchantService"></param>
        /// <param name="iProductService"></param>
        public TokenUserDistribution(IMerchantService iMerchantService, IProductService iProductService) : base(iMerchantService, iProductService) {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="merchant_id"></param>
        /// <param name="order_item"></param>
        /// <param name="is_distribute"></param>
        /// <returns></returns>
        public List<bind_merchant_item> Handler(long merchant_id, order_item_dto order_item, bool is_distribute = true) {
            var parents = GetParents(merchant_id, false);
            var product_ex = GetProduct(order_item);
            if (product_ex == null || product_ex.distribution_price <= 0) return new List<bind_merchant_item>();
            product_ex.distribution_price = product_ex.distribution_price * order_item.quantity;
            var userType = UserType.user;
            if (is_distribute) {
                //分销商品
                CalcSelfProfit(merchant_id, (product_ex.distribution_price * t_RequestMethod.token_user_level).RoundDown(2), order_item, t_RequestMethod.token_user_level);
                var merchant = parents.FirstOrDefault(c => c.usertype > UserType.user);
                if (merchant != null) {
                    CalcSelfProfit(merchant.id, (product_ex.distribution_price * t_RequestMethod.token_one_level).RoundDown(2), order_item, t_RequestMethod.token_one_level);
                    userType = merchant.usertype.Value;
                }
            } else {
                //app自购商品
                var merchant = parents.FirstOrDefault(c => c.usertype > UserType.user);
                if (merchant != null) {
                    //一级分销50%收益
                    userType = merchant.usertype.Value;
                    CalcSelfProfit(merchant.id, (product_ex.distribution_price * t_RequestMethod.token_one_level).RoundDown(2), order_item, t_RequestMethod.token_one_level);
                    var pmerchant = parents.FirstOrDefault(c => c.id != merchant.id && c.usertype > UserType.user);
                    if (pmerchant != null) {
                        //二级分销10%收益
                        CalcSelfProfit(pmerchant.id, (product_ex.distribution_price * t_RequestMethod.token_user_level).RoundDown(2), order_item, t_RequestMethod.token_user_level);
                        if (userType < pmerchant.usertype.Value)
                            userType = pmerchant.usertype.Value;
                    }
                }
            }
            userType = (userType == UserType.tokenMaker ? UserType.tokenNodeMall : userType);
            decimal bus_amount = t_RequestMethod.token_maker_user;
            foreach (var parent in parents) {
                if (parent.usertype.Value < userType)
                    continue;
                if (dicUses.Count > 0) {
                    var lastUser = dicUses.LastOrDefault();
                    if (parent.usertype < lastUser.Key)
                        continue;
                }
                if (dicUses.ContainsKey(parent.usertype.Value)) {
                    var lastUser = dicUses.LastOrDefault();
                    if (lastUser.Key == parent.usertype && !is_finish) {
                        var percent = (parent.usertype == UserType.tokenNodeMall ? t_RequestMethod.token_indirect_user : t_RequestMethod.token_top_percent);
                        var distibution_amount = (product_ex.distribution_price * percent).RoundDown(2);
                        if (distibution_amount > 0) {
                            binds.Add(new bind_merchant_item {
                                merchant_no = parent.merchant_no,
                                amount = distibution_amount,
                                product_id = order_item.product_id,
                                sku_id = order_item.sku_id ?? 0,
                                product_name = order_item.product_name,
                                freeze = true,
                                is_bus = true
                            });
                            log.Info(string.Format("间接用户：{0}，等级:{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), (order_item.distribute_price * t_RequestMethod.token_top_percent).RoundDown(2), t_RequestMethod.token_top_percent));
                        }
                        is_finish = true;
                    }
                    continue;
                }
                //等级【节点商城】获得10%收益
                if (parent.usertype == UserType.tokenNodeMall) {
                    bus_amount = bus_amount - t_RequestMethod.token_indirect_user;
                    var distibution_amount = (product_ex.distribution_price * bus_amount).RoundDown(2);
                    if (distibution_amount > 0) {
                        binds.Add(new bind_merchant_item {
                            merchant_no = parent.merchant_no,
                            amount = distibution_amount,
                            product_id = order_item.product_id,
                            sku_id = order_item.sku_id ?? 0,
                            product_name = order_item.product_name,
                            freeze = true,
                            is_bus = true
                        });
                        log.Info(string.Format("用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), (order_item.distribute_price * bus_amount).RoundDown(2), bus_amount));
                    }
                } else if (parent.usertype == UserType.tokenCountyAgent) {
                    decimal dis_amount = bus_amount - t_RequestMethod.token_top_percent;
                    var distibution_amount = (product_ex.distribution_price * dis_amount).RoundDown(2);
                    bus_amount = t_RequestMethod.token_top_percent;
                    if (distibution_amount > 0) {
                        binds.Add(new bind_merchant_item {
                            merchant_no = parent.merchant_no,
                            amount = distibution_amount,
                            product_id = order_item.product_id,
                            sku_id = order_item.sku_id ?? 0,
                            product_name = order_item.product_name,
                            freeze = true,
                            is_bus = true
                        });
                        log.Info(string.Format("用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), (order_item.distribute_price * dis_amount).RoundDown(2), dis_amount));
                    }
                } else if (parent.usertype == UserType.tokenCityAgent) {
                    var distibution_amount = (product_ex.distribution_price * bus_amount).RoundDown(2);
                    if (distibution_amount > 0) {
                        binds.Add(new bind_merchant_item {
                            merchant_no = parent.merchant_no,
                            amount = distibution_amount,
                            product_id = order_item.product_id,
                            sku_id = order_item.sku_id ?? 0,
                            product_name = order_item.product_name,
                            freeze = true,
                            is_bus = true
                        });
                        log.Info(string.Format("用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), (order_item.distribute_price * bus_amount).RoundDown(2), bus_amount));
                    }
                }
                dicUses.Add(parent.usertype.Value, parent);
            }
            return binds;
        }
    }
    /// <summary>
    /// 创客分销
    /// </summary>
    public class TokenMakerDistribution : DistributionBase, IDistribution {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="iMerchantService"></param>
        /// <param name="iProductService"></param>
        public TokenMakerDistribution(IMerchantService iMerchantService, IProductService iProductService) : base(iMerchantService, iProductService) {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="merchant_id"></param>
        /// <param name="order_item"></param>
        /// <param name="is_distribute"></param>
        /// <returns></returns>
        public List<bind_merchant_item> Handler(long merchant_id, order_item_dto order_item, bool is_distribute = true) {
            var userType = UserType.tokenMaker;
            var product_ex = GetProduct(order_item);
            if (product_ex == null || product_ex.distribution_price <= 0) return new List<bind_merchant_item>();
            product_ex.distribution_price = product_ex.distribution_price * order_item.quantity;
            //一级分销得50%收益
            CalcSelfProfit(merchant_id, (product_ex.distribution_price * t_RequestMethod.token_one_level).RoundDown(2), order_item, t_RequestMethod.token_one_level);
            var parents = GetParents(merchant_id, false);
            if (parents.Count() > 0)
                log.Info(parents.Select(c => "mobile：" + c.mobile + "，MerchantNo：" + c.merchant_no + "，UserType：" + c.usertype.ToDescription()).ToList().ToJson());

            //二级分销得10%收益
            var pmerchant = parents.FirstOrDefault(c => c.usertype > UserType.user);
            if (pmerchant != null) {
                CalcSelfProfit(pmerchant.id, (product_ex.distribution_price * t_RequestMethod.token_indirect_user).RoundDown(2), order_item, t_RequestMethod.token_indirect_user);
                if (userType < pmerchant.usertype)
                    userType = pmerchant.usertype.Value;
            }
            userType = (userType == UserType.tokenMaker ? UserType.tokenNodeMall : userType);
            decimal bus_amount = t_RequestMethod.token_maker_user;
            foreach (var parent in parents) {
                if (parent.usertype.Value < userType)
                    continue;
                if (dicUses.Count > 0) {
                    var lastUser = dicUses.LastOrDefault();
                    if (parent.usertype.Value < lastUser.Key)
                        continue;
                }
                //间接等级获取5%收益
                if (dicUses.ContainsKey(parent.usertype.Value)) {
                    var lastUser = dicUses.LastOrDefault();
                    if (parent.usertype.Value == lastUser.Key && !is_finish) {
                        var percent = (parent.usertype == UserType.tokenNodeMall ? t_RequestMethod.token_indirect_user : t_RequestMethod.token_top_percent);
                        var distribution_amount = (product_ex.distribution_price * percent).RoundDown(2);
                        if (distribution_amount > 0) {
                            binds.Add(new bind_merchant_item {
                                merchant_no = parent.merchant_no,
                                amount = distribution_amount,
                                product_id = order_item.product_id,
                                sku_id = order_item.sku_id ?? 0,
                                product_name = order_item.product_name,
                                freeze = true,
                                is_bus = true
                            });
                            log.Info(string.Format("间接用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), (order_item.distribute_price * t_RequestMethod.token_top_percent).RoundDown(2), t_RequestMethod.token_top_percent));
                        }
                        is_finish = true;
                    }
                    continue;
                }
                //等级【节点商城】获得10%收益
                if (parent.usertype == UserType.tokenNodeMall) {
                    bus_amount = bus_amount - t_RequestMethod.token_indirect_user;
                    var distribution_amount = (product_ex.distribution_price * bus_amount).RoundDown(2);
                    if (distribution_amount > 0) {
                        binds.Add(new bind_merchant_item {
                            merchant_no = parent.merchant_no,
                            amount = distribution_amount,
                            product_id = order_item.product_id,
                            sku_id = order_item.sku_id ?? 0,
                            product_name = order_item.product_name,
                            freeze = true,
                            is_bus = true
                        });
                        log.Info(string.Format("用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), (order_item.distribute_price * bus_amount).RoundDown(2), bus_amount));
                    }
                } else if (parent.usertype == UserType.tokenCountyAgent) {
                    decimal dis_amount = bus_amount - t_RequestMethod.token_top_percent;
                    bus_amount = t_RequestMethod.token_top_percent;
                    var distribution_amount = (product_ex.distribution_price * dis_amount).RoundDown(2);
                    if (distribution_amount > 0) {
                        binds.Add(new bind_merchant_item {
                            merchant_no = parent.merchant_no,
                            amount = distribution_amount,
                            product_id = order_item.product_id,
                            sku_id = order_item.sku_id ?? 0,
                            product_name = order_item.product_name,
                            freeze = true,
                            is_bus = true
                        });
                        log.Info(string.Format("用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), (order_item.distribute_price * dis_amount).RoundDown(2), dis_amount));
                    }
                } else if (parent.usertype == UserType.tokenCityAgent) {
                    var distribution_amount = (product_ex.distribution_price * bus_amount).RoundDown(2);
                    if (distribution_amount > 0) {
                        binds.Add(new bind_merchant_item {
                            merchant_no = parent.merchant_no,
                            amount = distribution_amount,
                            product_id = order_item.product_id,
                            sku_id = order_item.sku_id ?? 0,
                            product_name = order_item.product_name,
                            freeze = true,
                            is_bus = true
                        });
                        log.Info(string.Format("用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), (order_item.distribute_price * bus_amount).RoundDown(2), bus_amount));
                    }
                }
                dicUses.Add(parent.usertype.Value, parent);
            }
            return binds;
        }
    }
    /// <summary>
    /// 节点商城分销
    /// </summary>
    public class TokenNodeMallDistribution : DistributionBase, IDistribution {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="iMerchantService"></param>
        /// <param name="iProductService"></param>
        public TokenNodeMallDistribution(IMerchantService iMerchantService, IProductService iProductService) : base(iMerchantService, iProductService) {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="merchant_id"></param>
        /// <param name="order_item"></param>
        /// <param name="is_distribute"></param>
        /// <returns></returns>
        public List<bind_merchant_item> Handler(long merchant_id, order_item_dto order_item, bool is_distribute = true) {
            var product_ex = GetProduct(order_item);
            if (product_ex == null || product_ex.distribution_price <= 0) return new List<bind_merchant_item>();
            product_ex.distribution_price = product_ex.distribution_price * order_item.quantity;
            //节点商城一级分销得50%
            CalcSelfProfit(merchant_id, (product_ex.distribution_price * t_RequestMethod.token_one_level).RoundDown(2), order_item, t_RequestMethod.token_one_level);
            var parents = GetParents(merchant_id);
            if (parents.Count() > 0)
                log.Info(parents.Select(c => "mobile：" + c.mobile + "，MerchantNo：" + c.merchant_no + "，UserType：" + c.usertype.ToDescription()).ToList().ToJson());
            //创客以上等级，二级分销得10%
            var pmerchant = parents.FirstOrDefault(c => c.usertype > UserType.user && c.id != merchant_id);
            if (pmerchant != null) {
                CalcSelfProfit(pmerchant.id, (product_ex.distribution_price * t_RequestMethod.token_indirect_user).RoundDown(2), order_item, t_RequestMethod.token_indirect_user);
            }
            decimal total_amount = t_RequestMethod.token_maker_user;
            foreach (var parent in parents) {
                if (parent.usertype.Value < UserType.tokenNodeMall)
                    continue;
                if (dicUses.Count > 0) {
                    var lastUser = dicUses.LastOrDefault();
                    if (parent.usertype < lastUser.Key)
                        continue;
                }
                if (dicUses.ContainsKey(parent.usertype.Value)) {
                    var lastUser = dicUses.LastOrDefault();
                    if (lastUser.Key == parent.usertype.Value && !is_finish) {
                        var percent = parent.usertype.Value == UserType.tokenNodeMall ? t_RequestMethod.token_indirect_user + t_RequestMethod.token_top_percent : t_RequestMethod.token_top_percent;
                        var distribution_amount = (product_ex.distribution_price * percent).RoundDown(2);
                        if (distribution_amount > 0) {
                            binds.Add(new bind_merchant_item {
                                merchant_no = parent.merchant_no,
                                amount = distribution_amount,
                                product_id = order_item.product_id,
                                sku_id = order_item.sku_id ?? 0,
                                product_name = order_item.product_name,
                                freeze = true,
                                is_bus = true
                            });
                            log.Info(string.Format("间接用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), order_item.distribute_price * percent, percent));
                        }
                        is_finish = true;
                    }
                    continue;
                }
                //等级【节点商城】获得10%收益
                if (parent.usertype == UserType.tokenNodeMall) {
                    total_amount = total_amount - t_RequestMethod.token_indirect_user;
                    var distribution_amount = (product_ex.distribution_price * t_RequestMethod.token_indirect_user).RoundDown(2);
                    if (distribution_amount > 0) {
                        binds.Add(new bind_merchant_item {
                            merchant_no = parent.merchant_no,
                            amount = distribution_amount,
                            product_id = order_item.product_id,
                            sku_id = order_item.sku_id ?? 0,
                            product_name = order_item.product_name,
                            freeze = true,
                            is_bus = true
                        });
                        log.Info(string.Format("用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), (order_item.distribute_price * t_RequestMethod.token_indirect_user).RoundDown(2), t_RequestMethod.token_indirect_user));
                    }
                }
                //等级【超级节点、合伙人】获得5%收益
                if (parent.usertype == UserType.tokenCountyAgent) {
                    decimal dis_amount = total_amount - t_RequestMethod.token_top_percent;
                    total_amount = t_RequestMethod.token_top_percent;
                    var distribution_amount = (product_ex.distribution_price * dis_amount).RoundDown(2);
                    if (distribution_amount > 0) {
                        binds.Add(new bind_merchant_item {
                            merchant_no = parent.merchant_no,
                            amount = distribution_amount,
                            product_id = order_item.product_id,
                            sku_id = order_item.sku_id ?? 0,
                            product_name = order_item.product_name,
                            freeze = true,
                            is_bus = true
                        });
                        log.Info(string.Format("用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), order_item.distribute_price * dis_amount, dis_amount));
                    }
                } else if (parent.usertype == UserType.tokenCityAgent) {
                    var distribution_amount = (product_ex.distribution_price * total_amount).RoundDown(2);
                    if (distribution_amount > 0) {
                        binds.Add(new bind_merchant_item {
                            merchant_no = parent.merchant_no,
                            amount = distribution_amount,
                            product_id = order_item.product_id,
                            sku_id = order_item.sku_id ?? 0,
                            product_name = order_item.product_name,
                            freeze = true,
                            is_bus = true
                        });
                        log.Info(string.Format("用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), (order_item.distribute_price * total_amount).RoundDown(2), total_amount));
                    }
                }
                dicUses.Add(parent.usertype.Value, parent);
            }
            return binds;
        }
    }
    /// <summary>
    /// 超级节点分销
    /// </summary>
    public class TokenCountyAgentDistribution : DistributionBase, IDistribution {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="iMerchantService"></param>
        /// <param name="iProductService"></param>
        public TokenCountyAgentDistribution(IMerchantService iMerchantService, IProductService iProductService) : base(iMerchantService, iProductService) {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="merchant_id"></param>
        /// <param name="order_Item"></param>
        /// <param name="is_distribute"></param>
        /// <returns></returns>
        public List<bind_merchant_item> Handler(long merchant_id, order_item_dto order_Item, bool is_distribute = true) {
            var product_ex = GetProduct(order_Item);
            if (product_ex == null || product_ex.distribution_price <= 0) return new List<bind_merchant_item>();
            product_ex.distribution_price = product_ex.distribution_price * order_Item.quantity;
            //超级节点一级分销得50%
            CalcSelfProfit(merchant_id, (product_ex.distribution_price * t_RequestMethod.token_one_level).RoundDown(2), order_Item, t_RequestMethod.token_one_level);
            var parents = GetParents(merchant_id);
            if (parents.Count() > 0)
                log.Info(parents.Select(c => "mobile：" + c.mobile + "，MerchantNo：" + c.merchant_no + "，UserType：" + c.usertype.ToDescription()).ToList().ToJson());
            //创客以上级别，二级分销得10%
            var pmerchant = parents.FirstOrDefault(c => c.usertype > UserType.user && c.id != merchant_id);
            if (pmerchant != null) {
                CalcSelfProfit(pmerchant.id, (product_ex.distribution_price * t_RequestMethod.token_indirect_user).RoundDown(2), order_Item, t_RequestMethod.token_indirect_user);
            }
            foreach (var parent in parents) {
                if (parent.usertype.Value < UserType.tokenCountyAgent)
                    continue;
                //间接等级获得5%收益
                if (dicUses.ContainsKey(parent.usertype.Value)) {
                    var lastUser = dicUses.LastOrDefault();
                    if (lastUser.Key == parent.usertype && !is_finish) {
                        var distribution_amount = (product_ex.distribution_price * t_RequestMethod.token_top_percent).RoundDown(2);
                        if (distribution_amount > 0) {
                            binds.Add(new bind_merchant_item {
                                merchant_no = parent.merchant_no,
                                amount = distribution_amount,
                                product_id = order_Item.product_id,
                                sku_id = order_Item.sku_id ?? 0,
                                product_name = order_Item.product_name,
                                freeze = true,
                                is_bus = true
                            });
                            log.Info(string.Format("间接用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), (order_Item.distribute_price * t_RequestMethod.token_top_percent).RoundDown(2), t_RequestMethod.token_top_percent));
                        }
                        is_finish = true;
                    }
                    continue;
                }
                //等级为超级节点获得15%
                if (parent.usertype == UserType.tokenCountyAgent) {
                    var distribution_amount = (product_ex.distribution_price * (t_RequestMethod.token_top_percent + t_RequestMethod.token_indirect_user)).RoundDown(2);
                    if (distribution_amount > 0) {
                        binds.Add(new bind_merchant_item {
                            merchant_no = parent.merchant_no,
                            amount = distribution_amount,
                            product_id = order_Item.product_id,
                            sku_id = order_Item.sku_id ?? 0,
                            product_name = order_Item.product_name,
                            freeze = true,
                            is_bus = true
                        });
                        log.Info(string.Format("用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), (order_Item.distribute_price * (t_RequestMethod.token_top_percent + t_RequestMethod.token_indirect_user)).RoundDown(2), (t_RequestMethod.token_top_percent + t_RequestMethod.token_indirect_user)));
                    }
                } else if (parent.usertype == UserType.tokenCityAgent) {
                    //等级为合伙人节点获得5%
                    var distribution_amount = (product_ex.distribution_price * t_RequestMethod.token_top_percent).RoundDown(2);
                    if (distribution_amount > 0) {
                        binds.Add(new bind_merchant_item {
                            merchant_no = parent.merchant_no,
                            amount = distribution_amount,
                            product_id = order_Item.product_id,
                            sku_id = order_Item.sku_id ?? 0,
                            product_name = order_Item.product_name,
                            freeze = true,
                            is_bus = true
                        });
                        log.Info(string.Format("用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), (order_Item.distribute_price * t_RequestMethod.token_top_percent).RoundDown(2), t_RequestMethod.token_top_percent));
                    }
                }
                dicUses.Add(parent.usertype.Value, parent);
            }
            return binds;
        }
    }
    /// <summary>
    /// 城市级分公司合伙人
    /// </summary>
    public class TokenCityAgentDistribution : DistributionBase, IDistribution {
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="iMerchantService"></param>
        /// <param name="iProductService"></param>
        public TokenCityAgentDistribution(IMerchantService iMerchantService, IProductService iProductService) : base(iMerchantService, iProductService) {
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="merchant_id"></param>
        /// <param name="order_Item"></param>
        /// <param name="is_distribute"></param>
        /// <returns></returns>
        public List<bind_merchant_item> Handler(long merchant_id, order_item_dto order_Item, bool is_distribute = true) {
            var product_ex = GetProduct(order_Item);
            if (product_ex == null || product_ex.distribution_price <= 0) return new List<bind_merchant_item>();
            product_ex.distribution_price = product_ex.distribution_price * order_Item.quantity;
            //合伙人第一级分销得50%
            CalcSelfProfit(merchant_id, (product_ex.distribution_price * (t_RequestMethod.token_one_level)).RoundDown(2), order_Item, t_RequestMethod.token_one_level);
            //等级业绩获得20%
            CalcSelfProfit(merchant_id, (product_ex.distribution_price * (t_RequestMethod.token_maker_user)).RoundDown(2), order_Item, t_RequestMethod.token_indirect_user * 2, true);
            var parents = GetParents(merchant_id, false);
            var member = parents.FirstOrDefault(c => c.usertype > UserType.user);
            if (member != null) {
                //第二级分销得10%收益
                CalcSelfProfit(member.id, (product_ex.distribution_price * t_RequestMethod.token_indirect_user).RoundDown(2), order_Item, t_RequestMethod.token_indirect_user);
                log.Info(parents.Select(c => "mobile：" + c.mobile + "，MerchantNo：" + c.merchant_no + "，UserType：" + c.usertype.ToDescription()).ToList().ToJson());
            }
            foreach (var parent in parents) {
                if (parent.usertype.Value < UserType.tokenCityAgent)
                    continue;
                //合伙人第二级分销10%+间接得5%收益
                if (parent.usertype.Value == UserType.tokenCityAgent) {
                    var distribution_amount = (product_ex.distribution_price * (t_RequestMethod.token_top_percent + t_RequestMethod.token_indirect_user)).RoundDown(2);
                    if (distribution_amount > 0) {
                        binds.Add(new bind_merchant_item {
                            merchant_no = parent.merchant_no,
                            amount = distribution_amount,
                            product_id = order_Item.product_id,
                            sku_id = order_Item.sku_id ?? 0,
                            product_name = order_Item.product_name,
                            freeze = true,
                            is_bus = true
                        });
                        log.Info(string.Format("用户：{0}，等级：{1}，获得分润：{2}，比率：{3}", parent.name, parent.usertype.ToDescription(), (order_Item.distribute_price * (t_RequestMethod.token_top_percent + t_RequestMethod.token_indirect_user)).RoundDown(2), (t_RequestMethod.token_top_percent + t_RequestMethod.token_indirect_user)));
                    }
                    break;
                }
            }
            return binds;
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class DistributionFade {
        /// <summary>
        /// 计算商城分润算法
        /// </summary>
        /// <param name="componentContext"></param>
        /// <param name="merchant"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        public static List<bind_merchant_item> CalcMallProfits(IComponentContext componentContext, merchant_dto merchant, order_item_dto item) {
            long invite_id = 0;
            var user_type = UserType.user;
            bool is_distribute = false;
            var log = IocHelper.Get<ILogHelper>("info");
            if (item.distribution_id.HasValue && item.distribution_id.Value > 0) {
                invite_id = item.distribution_id.Value;
                user_type = item.dis_user.usertype.Value;
                is_distribute = true;
                log.Info(string.Format("分销用户：{0},用户等级：{1}", item.dis_user.mobile, item.dis_user.usertype.ToDescription()));
            } else if (merchant != null) {
                invite_id = merchant.id;
                user_type = merchant.usertype.Value;
                log.Info(string.Format("APP自购用户：{0},用户等级：{1}", merchant.mobile, merchant.usertype.ToDescription()));
            } else {
                return new List<bind_merchant_item>();
            }
            var _distribution = componentContext.ResolveKeyed<IDistribution>(user_type);
            var binds = _distribution.Handler(invite_id, item, is_distribute);
            return binds;
        }
    }
}
